//获取当前时间戳 reutrn YYYY-MM-DD
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        //var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
        return currentdate;
    };
//传入一个  YYYYY-MM-DD  前推和后退数以天数
    function nextDayFnc(startTime,y,z){
        var startTime = startTime;
        var startTime2 = startTime.split("-");
        var year = parseInt(startTime2[0]);
        var month = parseInt(startTime2[1]);
        var day = parseInt(startTime2[2]);
        var myDate=new Date();
        var setYesDay =  parseInt(myDate.setFullYear(year,month-1,day));
        if(z==1){
            var yesterday = parseInt(setYesDay-86400000*y);     //加减天数改变这个毫秒数
        }else if(z==2){
            var yesterday = parseInt(setYesDay+86400000*y);      //z==1时为-  z==2时为+
        }
        var ds = new Date(yesterday);
        var oldYear=ds.getYear()+1900;
        var oldMonth = ds.getMonth()+1;
        if (oldMonth<10){
            oldMonth = "0"+oldMonth;
        }else{
            oldMonth = oldMonth;
        }
        var oldDay = ds.getDate();
        if(oldDay<10){
            oldDay = "0"+oldDay;
        }else{
            oldDay = oldDay;
        }
        var yesDay = oldYear+"-"+oldMonth+"-"+oldDay;
        return yesDay;
    };
//传入 YYYYY-MM-DD 转成 yyyy年mm月dd日
    function parseDate(date){
        var newDate = date.split("-");
        return newDate[0]+"年"+newDate[1]+"月"+newDate[2]+"日";
    }
    var date = new Date();
    var lastWeek = new Date(date.getTime() - 6 * 24 * 3600 * 1000);
    var lastTwo = new Date(date.getTime() - 13 * 24 * 3600 * 1000);
    var tody = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    lastWeek = lastWeek.getFullYear() + "-" + (lastWeek.getMonth() + 1) + "-" + lastWeek.getDate();
    lastTwo = lastTwo.getFullYear() + "-" + (lastTwo.getMonth() + 1) + "-" + lastTwo.getDate();
    var yesterday = nextDayFnc(getNowFormatDate(), 1, 1);
    // 借用nextDayFnc方法将XXXX-X-X转化成XXXX-0X-0X格式
    tody = nextDayFnc(tody,0,1);
    lastWeek = nextDayFnc(lastWeek,0,1);
    lastTwo = nextDayFnc(lastTwo,0,1);
    $(".tody_btn").html("今日："+parseDate(tody));
	$(".tody_day").html("今日："+parseDate(tody));
	$(".yesterday_day").html("昨日："+parseDate(yesterday));
	$(".lastWeek_day").html("最近7日："+parseDate(lastWeek)+" — "+parseDate(tody));
	$(".lastTwo_day").html("最近14日："+parseDate(lastTwo)+" — "+parseDate(tody));
	
	
//	时间
	var beginDate=tody;
	var endDate=tody;

//点击事件
function selectDate(d,obj){
	if(d == 1){
		beginDate=tody;
		endDate=tody;
		$(".tody_btn").html($(obj).find("a").html());
	}else if(d == 2){
		beginDate=yesterday;
		endDate=tody;
		$(".tody_btn").html($(obj).find("a").html());
	}else if(d == 3){
		beginDate=lastWeek;
		endDate=tody;
		$(".tody_btn").html($(obj).find("a").html());
	}else if(d == 4){
		beginDate=lastTwo;
		endDate=tody;
		$(".tody_btn").html($(obj).find("a").html());
	}else if(d == 5){
		var test1=$("#test1").val();
		var test2=$("#test2").val();
		if(!test1){
			layer.msg("请先选择时间");
			return false;
		}
		if(!test2){
			layer.msg("请先选择时间");
			return false;
		}
		beginDate=test1;
		endDate=test2;
		$(".tody_btn").html("时间为："+parseDate(test1)+" — "+parseDate(test2));
		$(".tody_btn").parent().removeClass("open");
	}
	p=1;
	tiaozhuan(p);
}
//下载excel文件
function exportCsv(obj){
    //title ["","",""]
    var title = obj.title;
    //titleForKey ["","",""]
    var titleForKey = obj.titleForKey;
    var data = obj.data;
    var str = [];
    str.push(obj.title.join(",")+"\n");
    for(var i=0;i<data.length;i++){
        var temp = [];
        for(var j=0;j<titleForKey.length;j++){
            temp.push(data[i][titleForKey[j]]);
    }
    str.push(temp.join(",")+"\n");
    }
    var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(str.join(""));  
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    downloadLink.download = "export.csv"; 
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink); 
}



//分页方法
function paging(page,pageSize,total){
	page = Number(page);
	
	//最大页数
	var maxPage = Math.ceil(total/pageSize) || 1;
	if(page>maxPage){
		//取值不能超过maxPage
	    page = Math.min(page,maxPage);
	    tiaozhuan(page);
	}else if(page<1){
		//取值不能小于1
	    page = Math.max(page,1);
	    tiaozhuan(page);
	}else{
		//	当前页数
	$('.ui-paging-count').val(page);
	//首页的置灰处理
	$('.js-page-first').removeClass('ui-pager-disabled');
	//上一页
	$('.js-page-prev').removeClass('ui-pager-disabled').attr("data-page",page-1);
	//下一页
	$('.js-page-next').removeClass('ui-pager-disabled').attr("data-page",page+1);
	//最末页
	$('.js-page-last').removeClass('ui-pager-disabled').attr("data-page",maxPage);
	//总页数显示
	$('.js-page-total').text(maxPage);
	
	
	//当前显示多少页的处理
	$(".ui-select-pagesize").val(pageSize);
	//第一页的处理
	if(page == 1){
		$(".js-page-first").addClass('ui-pager-disabled').attr("data-page","");
		$(".js-page-prev").addClass('ui-pager-disabled').attr("data-page","");
	}
	if(page == maxPage){
		//最后一页的处理
		$(".js-page-last").addClass('ui-pager-disabled').attr("data-page","");
		$(".js-page-next").addClass('ui-pager-disabled').attr("data-page","");
	}
	}
	 
	
};
//下拉选择分页条数的操作
$('.ui-select-pagesize').on("change",function(){
	pageSize = $(this).val();	
	tiaozhuan(p);
});

//跳转到X页  blur
$(".ui-paging-count").on("blur",function(){
	p = $(this).val();
	tiaozhuan(p);
});

//上一页，下一页，首页，最末页的跳转
$('.ui-pager').on("click",function(){
	p = $(this).attr("data-page");
	tiaozhuan(p);
});


//获取交易类型
$('.jiaoyi_lx .jiaoyi_sx').on('click',function(){
	var dib = $(this).text();
	tradeType=$(this).find("a").attr('data-id');
	$('.jyshuxing').html(dib);
	p=1;
	tiaozhuan(p);
})
//下载文件
function download(){
	var param2 = "/advertiser/adStatistics/getBuyStatistics";
	var method2 = "post";
	var adComapyName = $('.jyshuxing').html();
	var datas2 = {page: p, pageSize: 1000,adComapyName:adComapyName};
	getAgentMsg2(param2,method2,datas2);
	exportCsv({
        title: ['合约资源订单名称','采买类型','平台类型','资源类型','投放时段','花费(元)','展示量','点击量','点击率(%)','CPM单价(元)','CPC单价(元)'],
        titleForKey: ['id','adverName','balance'],
        data: dataResult2.data.rows,
    },"合约交易报表.csv");
}

//财务记录列表
var p=1;
var tradeType=null;
var adverId='';
function tiaozhuan(p){	
	var pageSize=$('.ui-select-pagesize').val();
	var d={};
	d.page=p;
	d.pageSize=pageSize;
	d.createDateStart=beginDate;
	d.createDateEnd=endDate;
	d.resourceType=tradeType;

	$.ajax({
		url: url + "/advertiser/adStatistics/getBuyStatistics",
		type: 'POST',
		//		参数需转为字符串
		data: JSON.stringify(d),
		//		json跨域
		dataType: 'json',
		//		contentType类型为json
		contentType: "application/json",

		//		请求头加上X-Token 
		 beforeSend: function(XMLHttpRequest) {
			//		token 为页面所获取
			   
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		useDefaultXhrHeader: false,
		success: function(result) {
			if(result.code == '0') {
				var data=result.data.rows;
				var html="";
				for(var i in data){
					html += '<tr class="ng-scope"><td>'+data[i].orderName+'</td>';
					if(data[i].orderType == '1'){
						html += '<td class="ng-binding">CPM</td>';
					}else{
						html += '<td class="ng-binding">CPC</td>';
					}	
					if(data[i].operatSystem == '0'){
						html += '<td class="ng-binding">PC</td>';
					}else if(data[i].operatSystem == '1'){
						html += '<td class="ng-binding">IOS</td>';
					}else{
						html += '<td class="ng-binding">Android</td>';
					}
					if(data[i].resourceType == '0'){
						html += '<td class="ng-binding">保价保量</td>';
					}else{
						html += '<td class="ng-binding">保价不保量</td>';
					}	
					if(data[i].launchDateEnd == null && data[i].launchDateStart == null){
						html += '<td><p class="ng-scope">不限-不限</p></td>';
					}else if(data[i].launchDateEnd == null ){
						html += '<td><p class="ng-scope">'+data[i].launchDateStart+'-不限</p></td>';
					}else if(data[i].launchDateStart == null ){
						html += '<td><p class="ng-scope">不限-'+data[i].launchDateEnd+'</p></td>';
					}else{
						html += '<td><p class="ng-scope">'+data[i].launchDateStart+'-'+data[i].launchDateEnd+'</p></td>';
					}
					
					html += '<td><span class="ng-scope">'+data[i].expenditure+'</span></td>';

					html += '<td><span class="ng-scope">'+data[i].view+'</span></td><td><span class="ng-scope">'+data[i].click+'</span></td>';								
					html += '<td><span class="ng-scope">'+data[i].clickRate+'</span></td><td><span class="ng-scope">'+data[i].cpm+'</span></td><td><span class="ng-scope">'+data[i].cpc+'</span></td></tr>';
				}
				$(".heyuelist").html(html);
				var r=result.data.total;
					paging(p,pageSize,r);
			} else {
				isErr(result);
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
		
	});
}
tiaozhuan(p);
